package com.smart4j.framework.helper;

import com.smart4j.framework.annotation.Action;
import com.smart4j.framework.bean.Handler;
import com.smart4j.framework.bean.Request;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 *
 * @author 段誉
 * @create 2019-04-01 16:43
 */
public final class ControllerHelper {
  /**
   * 用于存放请求与处理器的映射关系(简称ActionMap)
   */
  private static final Map<Request, Handler> ACTION_MAP = new HashMap<>();

  static {
    //获取所有的Controller类
    Set<Class<?>> controllerClassSet = ClassHelper.getControllerSet();
    if (CollectionUtils.isNotEmpty(controllerClassSet)) {
      //变量controller类
      for (Class<?> controllerClass: controllerClassSet) {
        //获取controller类中定义的方法
        Method[] methods = controllerClass.getDeclaredMethods();
        //判断如果controller中没有方法则跳出本次循环
        if (ArrayUtils.isEmpty(methods)) {
          continue;
        }

        for (Method method: methods) {
          //判断方法上是否带有Action注解，不存在则结束本次循环
          if (!method.isAnnotationPresent(Action.class)) {
            continue;
          }
          //从Action注解中获取请求url和请求类型
          Action action = method.getAnnotation(Action.class);
          String requestMethod = action.method().toLowerCase();
          String requestPath = action.path();
          Request request = new Request(requestMethod, requestPath);
          Handler handler = new Handler(controllerClass, method);
          ACTION_MAP.put(request, handler);
        }

      }

    }

  }


  /**
   * 获取Handler
   */
  public static Handler getHandler(String requestMethod, String requestPath) {
    Request request = new Request(requestMethod, requestPath);
    return ACTION_MAP.get(request);
  }
}
